#include <math.h>

#include "map.h"

void saveMap(map_t map, const char *filename)
{
  int i = 0;
  FILE *mapFile = fopen(filename, "w");
  if (!mapFile)
  {
    printf("Unable to save map file.\n");
    return;
  }
  fprintf(mapFile, "%d %d", map.mapRows, map.mapCols);
  while (i < map.mapCols * map.mapRows)
  {
    if (i % map.mapCols == 0)
      fputc('\n', mapFile);
    fputc(map.map[i] + 48, mapFile);
    i++;
  }
  fclose(mapFile);
}

map_t loadMap(const char *filename)
{
  map_t map;
  int c = 0, p = 0;

  FILE *mapFile = fopen(filename, "r");
  if (!mapFile)
  {
    printf("Unable to open map file.\n");
    return map;
  }

  // First row contains the number of rows and columns
  fscanf(mapFile, "%u %u\n", &map.mapRows, &map.mapCols);
  map.map = (int *)malloc(map.mapRows * map.mapCols * sizeof(int));

  // subsequent rows have block index, or 0 for no block
  while ((c = fgetc(mapFile)) != EOF)
    if (c != '\n')
      map.map[p++] = (c - 48);

  // fclose(mapFile);
  return map;
}
